<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌信息" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="搜索关键字" prop="keywords" label-width="100px">
        <el-input
          v-model="queryParams.keywords"
          placeholder="请输入搜索关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品类型" align="center" prop="typeName" />
      <el-table-column label="商品主图" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品轮播图" align="center" prop="carouselImages" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.carouselImages" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品评论数" align="center" prop="commentCount" />
      <el-table-column label="商品收藏人气" align="center" prop="collectCount" />
      <el-table-column label="品牌信息" align="center" prop="brandName" />
      <el-table-column label="商品状态" align="center" prop="status">
        <template slot-scope="scope">
          <!--<dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>-->
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="0"
            inactive-value="1"
            @change="productStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>

      <el-steps :active="active" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="规格信息"></el-step>
        <el-step title="商品描述"></el-step>
      </el-steps>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div v-show="active == 0">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入商品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="搜索关键字" prop="keywords" label-width="100px">
                <el-input v-model="form.keywords" placeholder="请输入搜索关键字" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位" prop="unit">
                <el-input v-model="form.unit" placeholder="请输入单位" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品状态" prop="status" label-width="100px">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品类型" prop="type">
                <el-cascader
                  v-model="productTypeIds"
                  :options="productTypeListType"
                  :props="{ label: 'name',value:'id' }"
                  @change="changeProductTypeIds"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品品牌" prop="brand" label-width="100px">
                <el-select v-model="form.brand" placeholder="请选择">
                  <el-option
                    v-for="item in productBrandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="商品主图" prop="img">
            <image-upload v-model="form.img"/>
          </el-form-item>
          <el-form-item label="商品轮播图" prop="carouselImages">
            <image-upload v-model="form.carouselImages"/>
          </el-form-item>
        </div>

        <div v-show="active == 1">
          <el-form-item label="规格信息" prop="ruleAttrId">
            <el-select v-model="form.ruleAttrId" @change="changeRule" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in productRuleList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-row>
            <el-form :inline="true" :model="uniteSkuForm" class="demo-form-inline">
              <!--{label:"商品库存",prop:"stock"}
                span 属性：控制列占据的栅格宽度.将 24 等分的总宽度 平均分配 给所有列
              -->
              <el-col v-for="tableColumn in tableColumListTemplate" :span="24/tableColumListTemplate.length">
                <el-form-item :label="tableColumn.label">
                  <el-input-number v-if="tableColumn.prop !='image'" v-model="uniteSkuForm[tableColumn.prop]"
                                   :precision="2" :step="0.5" :max="999999"
                                   :min="0"
                                   size="small"
                  ></el-input-number>
                  <image-upload v-if="tableColumn.prop=='image'" v-model="uniteSkuForm[tableColumn.prop]"
                                :isShowTip.default="false"
                                :limit.dedault="1"
                                class="custom-image-uploader2"/>
                </el-form-item>
              </el-col>
              <el-col :span="5" :offset="20">
                <el-form-item>
                  <el-button type="primary" @click="clickSettings">一键设置</el-button>
                  <el-button type="primary" @click="clearSettings">一键清空</el-button>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-table v-loading="loading" :data="tableBodyList"  height="300px" @selection-change="handleSelectionChange">
                <el-table-column
                  v-for="column in tableColumnList" :label="column.label" :prop="column.prop" align="center"
                  class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <span v-if="column.prop.indexOf('prop') > -1 || column.prop =='number'"> {{scope.row[column.prop]}} </span>
                    <el-input v-if="column.prop.indexOf('prop') == -1 && column.prop !='image' && column.prop !='number'"
                              v-model="scope.row[column.prop]"/>
                    <image-upload v-if="column.prop=='image'" v-model="scope.row[column.prop]"
                                  :isShowTip.default="false"
                                  :limit.dedault="1"
                                  class="custom-image-uploader"/>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-button type="danger"
                               v-if="scope.row.stock > 0"
                               @click="tableBodyDelete(scope.$index)">售空</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>

        <div v-show="active == 2">
          <el-form-item label="商品描述" prop="productDesc">
            <!--富文本框-->
            <editor v-model="form.productDesc" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-top: 12px;" @click="last" v-show="active > 0">上一步</el-button>
        <el-button style="margin-top: 12px;" @click="next" v-show="active < 2">下一步</el-button>
        <el-button type="primary" @click="submitForm" v-show="active == 2">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/product/info"
import {listAllBrand} from "@/api/product/brand"
import {listTreeInfo} from "@/api/product/type";
import {listAllRule} from "@/api/product/rule";
import {tableId} from "quill/formats/table";
import index from "vuex";
export default {
  name: "Info",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      //商品SKU的表头循环
      tableColumnList:[],
      //所有规格信息
      productRuleList:[],
      //选中的值会以数组的形式存储在这个变量中
      productTypeIds:[],
      //商品类型列表 树级列表
      productTypeListType:[],
      //存储品牌数据
      productBrandList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //商品SKU的表头模版
      tableColumListTemplate:[
        {label:"商品库存",prop:"stock"},
        {label:"商品价格",prop:"price"},
        {label:"商品进价",prop:"purchasePrice"},
        {label:"商品售价",prop:"sellingPrice"},
        {label:"规格图片",prop:"image"},
        {label:"编号",prop:"number"},
        {label:"重量",prop:"weight"},
        {label:"体积",prop:"volume"}
      ],
      //商品SKU的表头模版默认值
      //通过上述实现效果展示我们发现除了前2列
      //后面字段值都是默认值
      //因此我们需要在代码中定义如下的一个数组
      // 2.定义商品sku的表格数模板，属于对象类型tableBodyListTemplate
      tableBodyListTemplate:{
        "stock":0.00,
        "price":0.00,
        "purchasePrice":0.00,
        "sellingPrice":0.00,
        "image":0.00,
        "number":0.00,
        "weight":0.00,
        "volume":0.00,
      },
      //商品sku的表格数据
      //1.定义接收商品sku的表格数据的数据模型，属于数组类型tableBodyList
      tableBodyList:[],
      //商品sku统一设置数据载体
      uniteSkuForm:{
        "stock":0.00,
        "price":0.00,
        "purchasePrice":0.00,
        "sellingPrice":0.00,
        "image":'',
        "number":0.00,
        "weight":0.00,
        "volume":0.00
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        brand: null,
        status: null,
        keywords: null,
      },
      // 表单参数
      form: {},
      //管理上一些下一些
      active:0,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        productDesc: [
          { required: true, message: "商品描述不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "商品类型不能为空", trigger: "change" }
        ],
        img: [
          { required: true, message: "商品主图不能为空", trigger: "blur" }
        ],
        carouselImages: [
          { required: true, message: "商品轮播图不能为空", trigger: "blur" }
        ],
        brand: [
          { required: true, message: "品牌信息不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "商品状态不能为空", trigger: "change" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        keywords: [
          { required: true, message: "搜索关键字不能为空", trigger: "blur" }
        ],
        ruleAttrId: [
          { required: true, message: "规格信息不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  //钩子函数,vue加载完后立马执行
  created() {
    //获取列表信息
    this.getList()
    //获取商品品牌动态下拉框
    this.initBrand()
    //初始化商品类型树级列表
    this.initTypeTree()
    //初始化规格下拉框
    this.initProductRuleList();
  },
  methods: {
    //便捷修改表格状态
    productStatus(row){
      // console.log(row.status)
      updateInfo({"id":row.id,"status":row.status}).then(res=>{
        //修改完之后进行列表的刷新查询
        this.getList();
        this.$modal.msgSuccess("修改成功");
      })
    },
    //删除单行的库存数量
    tableBodyDelete(index){
      this.tableBodyList[index].stock = 0;
    },
    //一键清除SKU属性值
    clearSettings(){
      //恢复上方的默认值
      this.uniteSkuForm={
        "stock":0.00,
        "price":0.00,
        "purchasePrice":0.00,
        "sellingPrice":0.00,
        "image":'',
        "number":0.00,
        "weight":0.00,
        "volume":0.00
      }
      this.tableBodyList.forEach((tableBody)=>{
        //将表格所有数据恢复成默认值
        for (let key in this.uniteSkuForm) {
          //将uniteSkuForm数组中的数据取出即表格上面的数据取出赋值给表格下面的数据
          tableBody[key] = this.uniteSkuForm[key]
        }
      })

    },
    //一键设置SKU属性值
    clickSettings(){
      console.log(this.uniteSkuForm)
      //tableBodyList
      this.tableBodyList.forEach((tableBody)=>{
        /*
        tableBody=image: ""
            number: 0
            price: 0
            prop0: "8G"
            prop1: "华为"
            purchasePrice: 0
            sellingPrice: 0
            stock: 0
            volume: 0
            weight: 0
     */
        // console.log(tableBody)
        for (let key in this.uniteSkuForm) {
          //将uniteSkuForm数组中的数据取出即表格上面的数据取出赋值给表格下面的数据
          tableBody[key] = this.uniteSkuForm[key]
        }
      })
    },
    /**
     *
     *
     * 3.在原来生成表头的changeRule函数中定义存储规格属性的数组let ruleAttrValueList = [];
     * 4.重置表格数据tableBodyList防止数组存储重复的数据
     * 5.在原来遍历ruleArr数组的forEach循环取出属性的大括中增加ruleAttrList，取出规格属性值数据例["8G","16G"]
     * 6.将ruleAttrList放到ruleAttrValueList集合中
     * 7.判断ruleAttrValueList是否有数据，没有数据则停止当前函数运行
     * 8.调用自定义函数generateTableData使用递归方式生成表格数据，ruleAttrValueList作为参数传递
     *
     *
     *
     * 12.如果所有规格还没处理完，需要处理规格，从attrValueList数组中，currentIndex作为索引获取当前规格的所有可选值，赋值给变量currentValues，值例如['8G','16G']
     * 13.使用固定字符串prop和currentIndex拼接生成属性名propName，如"prop0"、"prop1"
     * 14.遍历当前规格的所有可选值 currentValues = ['8G','16G']
     *    a.取出currentValues数组中的规格属性值
     *    b.创建新的规格组合对象newData
     *    c.遍历已有的规格数据currentData
     *    d.使用数组对象currentData调用hasOwnProperty函数判断key是否是currentData数组的自身属性（不是从原型链继承来的）
     *    e.如果是自身属性将currentData对应key的值放到newData对象中
     *    f.将value值放到propName对应的newData对象中，即添加当前规格值prop0 8G
     *    g.递归处理下一个规格即递归调用generateTableData函数，attrValueList、currentIndex + 1、newData、rowIndex作为函数参数
     * 15.将数据模型tableBodyList渲染到el-table标签视图上
     */
    //选中规格
    changeRule(){

      //每次改变清空数据
      this.tableColumnList = []
      // 规格属性二维数组
      let ruleAttrValueList = [];
      // 重置表格数据
      this.tableBodyList = [];
      /*
      productRuleList=[
          {
            createBy: "1"
            createTime: "2025-07-05 11:10:12"
            id: "0aa2822a42204feca31f338a1a9b7de3"
            name: "手机 - 内存,品牌"
            remark: null
            revision: null
            ruleAttr:
              "[{\"ruleType\":\"内存\",\"ruleAttrList\":[\"8G\",\"16G\"]},{\"ruleType\":\"品牌\",\"ruleAttrList\":[\"华为\",\"小米\"]}]"
            status: "0"
            updateBy: null
            updateTime: null
          }
        ]
      */
      //便利进行取值
      this.productRuleList.forEach(({id,ruleAttr})=>{

        //当选中的属性id与属性集合中id互相吻合
        if(id == this.form.ruleAttrId){
          //解析ruleAttr为数组类型
          /*
            ruleAttr:
                "[{\"ruleType\":\"内存\",\"ruleAttrList\":[\"8G\",\"16G\"]},
                {\"ruleType\":\"品牌\",\"ruleAttrList\":[\"华为\",\"小米\"]}]"
           */
          //进行字符串转集合
          let ruleArr = JSON.parse(ruleAttr);
          //进行遍历获取
          ruleArr.forEach(({ruleType,ruleAttrList},index)=>{
            //那么数组就会变成这样 tableColumnList=[{label:"内存",prop:"prop0"},{label:"品牌",prop:"prop1"}]
            this.tableColumnList.push({label:ruleType,prop:'prop'+index})
            //ruleAttrValueList=[['8G','16G'], ['华为','小米']]
            ruleAttrValueList.push(ruleAttrList);
          })
          //接下来进行tableColumnListTemplate和tableColumList的拼接
          this.tableColumListTemplate.forEach(val=>{this.tableColumnList.push(val)})
          //使用递归方式生产表格数据orEach(val=>this.tableColumnList.push(val))
        }
      })
      //如果没有规格直接返回
      if(ruleAttrValueList.length === 0) return;
      //递归生成表格数据
      this.generateTableData(ruleAttrValueList);
      //给tableBodyList中增加sku属性并将规格类型赋值给sku

      this.tableBodyList.forEach((tableBody)=>{
        let sku = [];
        /*
          tableBody={
          image: "http://127.0.0.1:9300/statics/2025/07/06/shouji_20250706220442A021.jpg"
          number: 2
          price: 1.5
          prop0: "8G"
          prop1: "华为"
          purchasePrice: 2
          sellingPrice: 1.5
          stock: 2.5
          volume: 1.5
          weight: 1.5}
        */
        for (let key in tableBody) {//key 表示image number price prop0 ...
          if(key.indexOf('prop') > -1){
            //说明key 是prop0 prop1
            //将key对应的值 "8G"  "华为" 放到sku中
            sku.push(tableBody[key])
          }
        }
        tableBody["sku"] = sku.toString();
      })
    },
    /*
      attrValueList = [['8G','16G'], ['华为','小米']]
      currentIndex从0开始，表示当前处理第几个规格属性
      currentData初始为空对象，用于保存当前生成的规格组合
      rowIndex是一个对象，用于记录当前行号（使用对象可以保持引用）
    */
    generateTableData(attrValueList,currentIndex,currentDate,rowIndex){
      debugger
      /**
       * 9.自定义函数generateTableData，参数有四个参数:
       *  attrValueList ：接收ruleAttrValueList例如 [['8G','16G'], ['华为','小米']]
       *  currentIndex从0开始，表示当前处理第几个规格属性
       *  currentData初始为空对象，用于保存当前生成的规格组合
       *  rowIndex是一个对象，用于记录当前行号（使用对象可以保持引用）
       *  10.使用typeof关键字对currentIndex、currentData、rowIndex参数进行处理，如果是'undefined',给
       *     currentIndex初始值0，currentData初始化值{},rowIndex初始化值{value：0}
       * @type {*|number}
       */
      //参数默认值处理
      currentIndex = typeof currentIndex == 'undefined' ? 0 : currentIndex;
      currentDate = typeof  currentDate == 'undefined' ? {} : currentDate;
      /**
       * 第1次满足基准条件：rowIndex.value 是0 → 第0行
       * 第2次满足基准条件：rowIndex.value 是1 → 第1行
       * 以此类推...
       */
      rowIndex = typeof rowIndex == 'undefined' ? {value:0} : rowIndex;
      // 基准条件: 所有规格都已经处理完毕['8G','16G']
      //11.判断currentIndex是否等于attrValueList数组长度，如果等于说明所有规格都已处理完毕
      if(currentIndex === attrValueList.length){
        //1）创建新行对象
        let newRow = {}
        //2）循环遍历tableBodyListTemplate即固定字段的模板数据 "stock":0.00
        for (let key in this.tableBodyListTemplate) {
          //a.使用数组对象调用hasOwnProperty函数判断key是否是tableBodyListTemplate数组的自身属性（不是从原型链继承来的）
          if(this.tableBodyListTemplate.hasOwnProperty(key)){
            //b.如果key是数组本身属性那么将key在数组tableBodyListTemplate的值即0.00放到newRow对象中，newRow[key]
              newRow[key] = this.tableBodyListTemplate[key];
          }
        }
        //合并当前规格组合数据
        for (let prop in currentDate) {
          if(currentDate.hasOwnProperty(prop)){
            newRow[prop] = currentDate[prop]
          }
        }
        //将新行添加到表格数据中 也就是一行都是 黄色 0 0 0 0 0
        this.tableBodyList.push(newRow);
        //然后行数加一
        rowIndex.value += 1;
        return;
      }
      // 获取当前规格的所有可选值，如['8G','16G']
      let currentValues = attrValueList[currentIndex];
      //生成属性名,如"prop0","prop1"
      let propName = "prop" + currentIndex;
      //3) 合并当前规格组合数据,遍历currentData即保存当前生成的规格组合的数组
      for (let i = 0; i < currentValues.length; i++) {
        let value = currentValues[i]; //value = '8G'
        //创建新的规格组合对象
        let newData = {};
        //复制已有的规格数据
        for (let dataKey in currentDate) {
          if(currentDate.hasOwnProperty(dataKey)){
            newData[dataKey] = currentDate[dataKey]
          }
        }
        //prop0 --- 8G
        newData[propName] = value;
        //循环递归调用
        this.generateTableData(attrValueList,currentIndex + 1,newData,rowIndex)
      }

      //5)rowIndex.value进行加1重新赋值给rowIndex.value
      //6)使用return结束当前函数调用即递归结束条件


      //a.使用数组对象currentData调用hasOwnProperty函数判断prop是否是currentData对象的自身属性（不是从原型链继承来的）
      //  currentData = {prop0: '8G', prop1: '华为'}
      //b.将currentData[prop]赋值给newRow[prop],最后newRow类似:
      //{"prop0":"8G","prop1":"16G","stock":0.00,"price":0.00,"purchasePrice":0.00,"sellingPrice":0.00,"image":0.00,
      //"number":0.00,"weight":0.00,"volume":0.00}
      //4) 将新行newRow添加到存储表格数据中tableBodyList数组中，rowIndex.value作为索引，存储完毕之后tableBodyList数组类似:

      //tableBodyList=[{"prop0":"8G","prop1":"16G","stock":0.00,"price":0.00,"purchasePrice":0.00,"sellingPrice":0.00,"image":0.00,
      //"number":0.00,"weight":0.00,"volume":0.00}]
      console.log(this.tableBodyList)
    },
    //初始化规格下拉框
    initProductRuleList(){
      listAllRule().then(res=>{
        //将值赋给规格列表
        this.productRuleList = res.data;
        //接下来将集合进行循环遍历 格式 手机-内存,颜色
        this.productRuleList.forEach((productRule)=>{
          let ruleAttr = JSON.parse(productRule.ruleAttr);
          let ruleTypeAttr = [];
          ruleAttr.forEach(({ruleType})=>{
            ruleTypeAttr.push(ruleType)
          })
          //将格式 手机-内存,颜色
          productRule.name += "-" + ruleTypeAttr.toString();
        })
        console.log(this.productRuleList)
      })
    },
    changeProductTypeIds(typeIds){
      // console.log(value);
      //['592a5a385a9f4fc1afc7d0e30204dd88', '59bfd5d4b74f46cebc7422893d952387',
      // '050c25e293f243dda81340873a515ed7', __ob__: Observer]
      //this.form.type 表示商品类型typeIds[typeIds.length - 1]表示最小的子级商品id赋值给type
      //这里就是050c25e293f243dda81340873a515ed7
      this.form.type=typeIds[typeIds.length - 1]
      this.form.typeIds=typeIds.toString()//提交form表单后端有属性接收
      console.log(this.form)
    },
    //初始化商品类型树级列表
    initTypeTree(){
      listTreeInfo().then(res=>{
        this.productTypeListType = res.data
        console.log(res)
      })
    },
    //获取商品品牌动态下拉框
    initBrand(){
      listAllBrand().then(res=>{
        this.productBrandList = res.data
      })
    },
    //上一步
    last() {
      this.active--;
    },
    //下一步
    next() {
      let isValid = true;
      //当页面为初始下标为0的时候
      if(this.active == 0){
        //进行校验判断
          this.$refs['form'].validateField(["name","keywords","unit","status","type","brand"],
          (valid) => {
            if (!(valid == null || valid == '')) {
              isValid = false;
            }
          });
      }else if(this.active == 1){
        //继续验证规格信息
        this.$refs['form'].validateField(["ruleAttrId"],
          (valid) => {
            if (!(valid == null || valid == '')) {
              isValid = false;
            }
          });
      }
      if(isValid){
        this.active++;
      }
    },
    /** 查询商品信息列表 */
    getList() {
      this.loading = true
      listInfo(this.queryParams).then(response => {
        this.infoList = response.data.rows
        this.total = response.data.total
        this.loading = false
        console.log(response.data.rows)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        productDesc: null,
        type: null,
        typeIds: null,
        img: null,
        carouselImages: null,
        commentCount: null,
        collectCount: null,
        brand: null,
        status: null,
        unit: null,
        keywords: null,
        ruleAttrId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
      //解决当我再次点击添加的时候，页面还有上次修改时候的数据并没有重置:
      //首先进行步骤的初始化 回到默认的0
      this.active = 0;
      //将TableBodyList清空
      this.tableBodyList = [];
      //将联级选择框进行请空
      this.productTypeIds = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加商品信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data
        //联级选择框回显
        this.productTypeIds = this.form.typeIds.split(",")
        //生成表头,清空上次存储的数据
        this.tableColumnList = []
        //这是之前原来的表头代码
        //目的是为了将表头数据就行回显
        //代码直接复用就行，应为数据是从后端查出来的
        /*
      productRuleList=[
          {
            createBy: "1"
            createTime: "2025-07-05 11:10:12"
            id: "0aa2822a42204feca31f338a1a9b7de3"
            name: "手机 - 内存,品牌"
            remark: null
            revision: null
            ruleAttr:
              "[{\"ruleType\":\"内存\",\"ruleAttrList\":[\"8G\",\"16G\"]},{\"ruleType\":\"品牌\",\"ruleAttrList\":[\"华为\",\"小米\"]}]"
            status: "0"
            updateBy: null
            updateTime: null
          }
        ]
      */
        this.productRuleList.forEach(({id,ruleAttr})=>{
          if(id == this.form.ruleAttrId){
            let ruleArr = JSON.parse(ruleAttr);
            /*  例如:
             ruleAttr=
             [{"ruleType":"内存","ruleAttrList":["8G","16G"]},
             {"ruleType":"品牌","ruleAttrList":["华为","小米"]}]*/
            // 遍历数组生成表头
            ruleArr.forEach(({ruleType,ruleAttrList},index) => {
              this.tableColumnList.push({label: ruleType,prop: 'prop'+index});
            })
            //添加固定列
            this.tableColumListTemplate.forEach(val=> this.tableColumnList.push(val))
          }
        })
        //接下来这个步骤就是将那很多很多的列表回显值的
        //将后端响应的skuList赋值给tableBodyList
        //this.tableBodyList = response.data.skuiList
        let skuList = response.data.skuList;
        skuList.forEach(skuObj=>{
          //skuObj.sku = "16G，华为"
          let skuArr = skuObj.sku.split(",");
          //遍历数组拿到值 skuVal = 16G,index = 0
          skuArr.forEach((skuVal,index)=>{
            /**
             * 第一遍执行完:
             * skuObj={createBy:"1",number:"112a01920202011",prop0:"16G",prop1:"华为"}
             */
            skuObj["prop"+index] = skuVal
          })
        })
        this.tableBodyList = skuList
        this.open = true
        this.title = "修改商品信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        //列表中没有sku,我们最终要添加到商品信息表和商品中间表
        console.log(this.tableBodyList);
        if (valid) {
          //将this.tableList中的值赋给form数组中的skuList
          this.form.skuList = this.tableBodyList
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
::v-deep .custom-image-uploader2 .el-upload--picture-card {
  width: 85px;
  height: 85px;
  line-height: 85px;
}

/* 调整预览图片大小 */
::v-deep .custom-image-uploader2 .el-upload-list__item {
  width: 85px;
  height: 85px;
}

/* 调整上传卡片大小 */
::v-deep .custom-image-uploader .el-upload--picture-card {
  width: 60px;
  height: 60px;
  line-height: 60px;
}

/* 调整预览图片大小 */
::v-deep .custom-image-uploader .el-upload-list__item {
  width: 60px;
  height: 60px;
}
</style>
